<template>
  <div class="app-container">
    <div v-loading="loading" class="order-detail-container">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>订单基本信息</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回列表</el-button>
        </div>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-item">
              <span class="detail-label">订单号：</span>
              <span class="detail-value">{{ orderDetail.order_number }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="detail-label">订单状态：</span>
              <el-tag :type="statusTypeMap[orderDetail.status]">{{ statusLabelMap[orderDetail.status] }}</el-tag>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="detail-label">创建时间：</span>
              <span class="detail-value">{{ orderDetail.create_time | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-item">
              <span class="detail-label">物流公司：</span>
              <span class="detail-value">{{ orderDetail.logistics_company ? orderDetail.logistics_company.name : '未知' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="detail-label">订单金额：</span>
              <span class="detail-value">¥{{ orderDetail.total_amount }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="detail-label">保险方案：</span>
              <span class="detail-value">{{ orderDetail.insurance_coverage ? orderDetail.insurance_coverage.name : '无' }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="box-card" style="margin-top: 20px;">
        <div slot="header" class="clearfix">
          <span>寄件人信息</span>
        </div>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-item">
              <span class="detail-label">寄件人：</span>
              <span class="detail-value">{{ orderDetail.sender_name }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="detail-label">联系电话：</span>
              <span class="detail-value">{{ orderDetail.sender_phone }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="detail-label">寄件网点：</span>
              <span class="detail-value">{{ orderDetail.express_outlet ? orderDetail.express_outlet.name : '未知' }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <div class="detail-item">
              <span class="detail-label">寄件地址：</span>
              <span class="detail-value">{{ orderDetail.sender_address }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="box-card" style="margin-top: 20px;">
        <div slot="header" class="clearfix">
          <span>收件人信息</span>
        </div>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-item">
              <span class="detail-label">收件人：</span>
              <span class="detail-value">{{ orderDetail.receiver_name }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="detail-label">联系电话：</span>
              <span class="detail-value">{{ orderDetail.receiver_phone }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="detail-label">目的网点：</span>
              <span class="detail-value">{{ orderDetail.destination_outlet ? orderDetail.destination_outlet.name : '未知' }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <div class="detail-item">
              <span class="detail-label">收件地址：</span>
              <span class="detail-value">{{ orderDetail.receiver_address }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="box-card" style="margin-top: 20px;">
        <div slot="header" class="clearfix">
          <span>物品信息</span>
        </div>
        <el-table :data="orderItems" border style="width: 100%">
          <el-table-column prop="item.name" label="物品名称" width="180" />
          <el-table-column prop="item.category.name" label="物品类别" width="180" />
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column prop="weight" label="重量(kg)" width="120" />
          <el-table-column prop="volume" label="体积(m³)" width="120" />
          <el-table-column prop="declared_value" label="申报价值" width="120">
            <template slot-scope="scope">
              ¥{{ scope.row.declared_value }}
            </template>
          </el-table-column>
          <el-table-column prop="item.description" label="物品描述" />
        </el-table>
      </el-card>

      <el-card class="box-card" style="margin-top: 20px;">
        <div slot="header" class="clearfix">
          <span>物流轨迹</span>
          <el-button
            v-if="canAddTrack"
            style="float: right; margin-left: 10px;"
            type="primary"
            size="small"
            @click="handleAddTrack"
          >
            添加轨迹
          </el-button>
        </div>
        <el-timeline>
          <el-timeline-item
            v-for="(track, index) in trackList"
            :key="index"
            :timestamp="track.create_time | parseTime('{y}-{m}-{d} {h}:{i}')"
            :type="getTimelineItemType(track.status)"
          >
            <el-card>
              <h4>{{ statusLabelMap[track.status] }}</h4>
              <p>{{ track.description }}</p>
              <p v-if="track.location">位置: {{ track.location }}</p>
              <p v-if="track.operator">操作人: {{ track.operator }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
        <pagination
          v-show="trackTotal>0"
          :total="trackTotal"
          :page.sync="trackQuery.pageNum"
          :limit.sync="trackQuery.pageSize"
          @pagination="getTrackInfo"
        />
      </el-card>

      <!-- 添加物流轨迹对话框 -->
      <el-dialog title="添加物流轨迹" :visible.sync="trackDialogVisible">
        <el-form
          ref="trackForm"
          :model="trackForm"
          :rules="trackRules"
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item label="轨迹状态" prop="status">
            <el-select v-model="trackForm.status" placeholder="请选择轨迹状态">
              <el-option
                v-for="(label, value) in nextStatusOptions"
                :key="value"
                :label="label"
                :value="value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="位置" prop="location">
            <el-input v-model="trackForm.location" placeholder="请输入位置信息" />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="trackForm.description" type="textarea" :rows="3" placeholder="请输入轨迹描述" />
          </el-form-item>
          <el-form-item label="操作人" prop="operator">
            <el-input v-model="trackForm.operator" placeholder="请输入操作人" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="trackDialogVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="submitTrack">
            确认
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { http } from '@/api'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'

export default {
  name: 'OrderDetail',
  components: { Pagination },
  filters: {
    parseTime
  },
  data() {
    return {
      loading: true,
      orderId: null,
      orderDetail: {},
      orderItems: [],
      trackList: [],
      trackTotal: 0,
      trackQuery: {
        pageNum: 1,
        pageSize: 10,
        order_id: undefined
      },
      statusTypeMap: {
        pending: 'info',
        processing: 'primary',
        shipped: 'success',
        in_transit: 'warning',
        out_for_delivery: 'warning',
        delivered: 'success',
        cancelled: 'danger'
      },
      statusLabelMap: {
        pending: '待处理',
        processing: '处理中',
        shipped: '已发货',
        in_transit: '运输中',
        out_for_delivery: '派送中',
        delivered: '已送达',
        cancelled: '已取消'
      },
      trackDialogVisible: false,
      trackForm: {
        express_order_id: null,
        status: '',
        location: '',
        description: '',
        operator: ''
      },
      trackRules: {
        status: [{ required: true, message: '请选择轨迹状态', trigger: 'change' }],
        location: [{ required: true, message: '请输入位置信息', trigger: 'blur' }],
        description: [{ required: true, message: '请输入轨迹描述', trigger: 'blur' }]
      },
      nextStatusOptions: {}
    }
  },
  computed: {
    canAddTrack() {
      // 只有非取消和非已送达的订单才能添加轨迹
      return this.orderDetail.status &&
             this.orderDetail.status !== 'cancelled' &&
             this.orderDetail.status !== 'delivered'
    }
  },
  created() {
    this.orderId = this.$route.params.id
    if (this.orderId) {
      this.getOrderDetail()
      this.getOrderItems()
      this.getTrackInfo()
    } else {
      this.$message.error('订单ID不能为空')
      this.goBack()
    }
  },
  methods: {
    getOrderDetail() {
      this.loading = true
      http.expressOrder.read(this.orderId).then(response => {
        this.orderDetail = response.data
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    getOrderItems() {
      // 假设有一个获取订单物品的API
      http.expressOrder.read(this.orderId).then(response => {
        if (response.data && response.data.order_items) {
          this.orderItems = response.data.order_items
        }
      })
    },
    getTrackInfo() {
      this.trackQuery.order_id = this.orderId
      http.expressOrder.getTrackInfo(this.trackQuery).then(response => {
        this.trackList = response.data.rows || []
        this.trackTotal = response.data.count || 0
      })
    },
    goBack() {
      this.$router.push('/order/list')
    },
    getTimelineItemType(status) {
      switch (status) {
        case 'delivered':
          return 'success'
        case 'cancelled':
          return 'danger'
        case 'pending':
          return 'info'
        default:
          return 'primary'
      }
    },
    handleAddTrack() {
      this.trackForm = {
        express_order_id: this.orderId,
        status: '',
        location: '',
        description: '',
        operator: ''
      }

      // 根据当前订单状态设置可选的下一状态
      this.setNextStatusOptions(this.orderDetail.status)

      this.trackDialogVisible = true
    },
    setNextStatusOptions(currentStatus) {
      // 根据当前状态设置可以更新的下一状态
      switch(currentStatus) {
        case 'pending':
          this.nextStatusOptions = {
            processing: '处理中',
            cancelled: '已取消'
          }
          break
        case 'processing':
          this.nextStatusOptions = {
            shipped: '已发货',
            cancelled: '已取消'
          }
          break
        case 'shipped':
          this.nextStatusOptions = {
            in_transit: '运输中',
            cancelled: '已取消'
          }
          break
        case 'in_transit':
          this.nextStatusOptions = {
            out_for_delivery: '派送中'
          }
          break
        case 'out_for_delivery':
          this.nextStatusOptions = {
            delivered: '已送达'
          }
          break
        default:
          this.nextStatusOptions = {}
      }
    },
    submitTrack() {
      this.$refs.trackForm.validate((valid) => {
        if (valid) {
          http.logisticsTrack.addTrack(this.trackForm).then(() => {
            this.trackDialogVisible = false
            this.$notify({
              title: '成功',
              message: '物流轨迹添加成功',
              type: 'success',
              duration: 2000
            })

            // 更新订单状态
            const data = {
              id: this.orderId,
              status: this.trackForm.status,
              remark: this.trackForm.description
            }

            http.expressOrder.updateStatus(data).then(() => {
              // 刷新订单详情和轨迹信息
              this.getOrderDetail()
              this.getTrackInfo()
            })
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.order-detail-container {
  padding: 20px;
}
.detail-item {
  margin-bottom: 15px;
}
.detail-label {
  font-weight: bold;
  margin-right: 10px;
}
.detail-value {
  color: #606266;
}
.box-card {
  margin-bottom: 20px;
}
</style>
